﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MySql.Data.MySqlClient;
using LdExpress;
using System.Text.RegularExpressions;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    public string ContainerPage = "./Tinh.aspx";
    public string strCondition = "";
    public int NumOfItemsPerPage = 100;
    public string strPager = "";
    public string strIDs = "";
    public string strError = "";
    public string strMess = "";
    public int nPermissions = 0;
    public int nPage = 1;
    public string strPageID = "page_number";
    public string strLetter = "letter";
    public string strAlphaBet = "";
    string strChar = "";
    string strExcluded = "PortsID";
    public string strPartQuery = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["Province"] != null && int.Parse(Session["Province"].ToString()) > 0)
        {
            if (Session["Province"] != "") nPermissions = int.Parse(Session["Province"].ToString());
        }
        else
            Response.Redirect("Login.aspx");
        try
        {

            if (Request.QueryString[strLetter] != null)
            {
                strChar = Request.QueryString[strLetter].ToString();
                strCondition = " AND Name like '" + strChar + "%'";
            }
        }
        catch
        {
            strChar = "";
        }

        try
        {

            if (Request.QueryString[strPageID] != null)
                nPage = int.Parse(Request.QueryString[strPageID]);
        }
        catch
        {
            nPage = 1;
        }
        if (nPage <= 0) nPage = 1;

        if (Session["sesserchRegion"] == null) Session["sesserchRegion"] = "";
        if (!Page.IsPostBack)
        {
            if (Request.QueryString["action"] == "delete")
            {
                Tinh obj = new Tinh();
                obj.ID = long.Parse(Request.QueryString["ID"]);
                obj.Load(GV.cn, GV.trans);
                obj.Delete(GV.cn, GV.trans);
                Response.Redirect("Tinh.aspx");
            }
            if (nPermissions < 3) btnSave.Visible = false;
            #region Build List
            int nNumOfPages = 0;

            DataTable dtList;
            BuildList(strCondition, NumOfItemsPerPage, nPage, out nNumOfPages, out dtList, null, null);
            if (nPage > nNumOfPages) nPage = 1;

            rptData.DataSource = dtList;
            rptData.DataBind();
            #endregion
            #region Build Pager
            CommonFunctions.BuildPager(Request, nNumOfPages, nPage, strPageID, ContainerPage, out strPager);
            #endregion
            CommonFunctions.BuildAphabetSearch(Request, ContainerPage, strLetter, strChar, strExcluded, out strAlphaBet);
        }

    }
    //protected void loadPorts()
    //{
    //    Ports obj = new Ports();
    //    obj.ID = long.Parse(Request.QueryString["PortsID"]);
    //    obj.Load(GV.cn, GV.trans);
    //    txtPorts.Text = HttpUtility.HtmlDecode(obj.Name);
    //    txtCode.Text = HttpUtility.HtmlDecode(obj.Code);
    //    txtDescription.Text = HttpUtility.HtmlDecode(obj.Description);
    //    txtCity.Text = HttpUtility.HtmlDecode(obj.City);
    //    txtCountry.Text = HttpUtility.HtmlDecode(obj.Country);
    //    txtRegion.Text = HttpUtility.HtmlDecode(obj.Region);
    //    //drdBillExCustID.SelectedValue.ToString();        
    //    // int.Parse(drProvince.SelectedValue)        
    //}

    protected void btnSave_Click(object sender, EventArgs e)
    {
        strError = "";
        strMess = "";
        Tinh obj = null;
        foreach (RepeaterItem item in rptData.Items)
        {
            obj = new Tinh();
            string strID = ((HiddenField)item.FindControl("txtID")).Value.Trim();
            string strMa = ((TextBox)item.FindControl("txtMa")).Text.Trim();
            string strTen = ((TextBox)item.FindControl("txtTen")).Text.Trim();
            long lVungmien = long.Parse(((DropDownList)item.FindControl("drvungmien")).Text.ToString());
            if (strID.Length > 0)//Update
            {
                bool isPlanSave = false;

                obj.ID = long.Parse(strID);
                obj.Load(GV.cn, GV.trans);
                if (obj.Ma != strMa)
                {
                    obj.Ma = strMa;
                    isPlanSave = true;
                }
                if (obj.Ten != strTen)
                {
                    obj.Ten = strTen;
                    isPlanSave = true;
                }
                if (obj.VungID != lVungmien)
                {
                    obj.VungID = lVungmien;
                    isPlanSave = true;
                }
                if (isPlanSave)
                {
                    obj.Save(GV.cn, GV.trans);
                }

            }
            if (strTen.Length > 0 && strID.Length == 0)
            {
                obj.ID = -1;
                obj.Ma = strMa;
                obj.Ten = strTen;
                obj.VungID = lVungmien;
                obj.Save(GV.cn, GV.trans);
            }
            DataSet ds = null;
            string sqlCommand = "SELECT tbl_tinh.Ten AS TenTinh, tbl_huyen.Ten AS TenHuyen FROM tbl_tinh,tbl_huyen WHERE tbl_huyen.TinhID =tbl_tinh.ID;";
            ds = DBModule.ExecuteQuery(sqlCommand, GV.cn, GV.trans);
            string strName = "";
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                if (strName.Length > 0) strName += ",";
                strName += "\"" + DBModule.ucFirstAllWords(DBModule.UnicodeToPlain(dr["TenHuyen"].ToString().Trim())) + ", " + DBModule.ucFirstAllWords(DBModule.UnicodeToPlain(dr["TenTinh"].ToString().Trim())) + "\"";
            }
            string strCountFile = Server.MapPath("./") + "\\Assets\\Js\\DomesticPOR.js";

            StreamWriter sw;

            strName = "var por = [" + strName + "];";
            sw = new StreamWriter(strCountFile, false);
            sw.Write(strName);
            sw.Close();
        }

    }

    private void BuildList(string strCondition, int NumOfItemsPerPage, int PageNo, out int nNumOfPages, out DataTable dtList, MySqlConnection cn, MySqlTransaction trans)
    {
        DataSet ds = null;
        dtList = new DataTable();
        dtList.Columns.Add("Index");
        dtList.Columns.Add("ID");
        dtList.Columns.Add("Ma");
        dtList.Columns.Add("Ten");
        dtList.Columns.Add("VungID");
        dtList.Columns.Add("Action");
        //Get List by SoIDs
        nNumOfPages = 0;

        // if (strCondition == "") strCondition = "All";
        Tinh obj = new Tinh();
        obj.GetList(strCondition, "Ten", NumOfItemsPerPage, PageNo, out nNumOfPages, out ds, GV.cn, GV.trans);

        string strAllQueryString = "";
        string[] strValues = new string[] { "", "", "", "", "0", "" };
        dtList.Rows.Add(strValues);
        foreach (string strKey in Request.QueryString.AllKeys)
        {
            if (strKey != null)
            {
                if ((strKey.ToLower() != "action") && (strKey.ToLower() != "id"))
                    strAllQueryString = strAllQueryString + "&" + strKey + "=" + Request.QueryString[strKey].ToString();
            }
        }

        if (strAllQueryString.Length >= 1)
            strAllQueryString = strAllQueryString.Substring(1);

        if (ds != null)
        {
            int count = 0;
            if (Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "")
            {
                int pagenumber = 1;
                try
                {
                    pagenumber = int.Parse(Request.QueryString["page_number"]);
                    count = NumOfItemsPerPage * (pagenumber - 1);
                }
                catch { count = 0; }
            }
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                count++;
                //string strSTT = dr["Sort"].ToString();
                string strIndex = count.ToString();
                string ID = dr["ID"].ToString();
                string Ma = dr["Ma"].ToString();
                string Ten = dr["Ten"].ToString();
                string VungID = dr["VungID"].ToString();
                string strAction = "";
                if (nPermissions > 7)
                {
                    if (strAction.Length > 0) strAction += " - ";
                    strAction += "<a href=\"javascript:doDelete('" + System.Web.HttpUtility.HtmlEncode(dr["ID"].ToString()) + "')\">Xóa</a>";
                }
                strValues = new string[] { strIndex, ID, Ma, Ten, VungID, strAction };
                dtList.Rows.Add(strValues);
            }
        }
    }
    protected void rptData_ItemDataBound(Object sender, RepeaterItemEventArgs e)
    {
        DropDownList drd = (DropDownList)e.Item.FindControl("drvungmien");
        HiddenField hidVungID = (HiddenField)e.Item.FindControl("hidVung");
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            //drd.Items.Add(new ListItem("Chọn Cảng", "-1"));
            //drd.Items.Add(new ListItem("Hải Phòng", "1"));
            //drd.Items.Add(new ListItem("Đà Nẵng", "2"));
            //drd.Items.Add(new ListItem("Hồ Chí Minh", "3"));
            //drd.Items.Add(new ListItem("Quy Nhơn", "4"));
            //drd.Items.Add(new ListItem("Cái Lân", "5"));
            DataSet ds = null;
            Location.DoSearch("", "", out ds, GV.cn, GV.trans);
            drd.DataSource = ds.Tables[0];
            drd.DataTextField = ds.Tables[0].Columns["Name"].ToString();
            drd.DataValueField = ds.Tables[0].Columns["ID"].ToString();
            drd.DataBind();
            drd.Items.Insert(0, new ListItem("Chọn cảng", "-1"));
            try
            {
                if (int.Parse(hidVungID.Value.ToString()) > 0)
                    drd.SelectedValue = hidVungID.Value;
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
            //Response.Write(hidVungID.Value+"<br>");

        }
    }
    //protected void btnSearch_Click(object sender, EventArgs e)
    //{
    //    string strCondition = "";
    //    if (txtPortSearch.Text.ToString().Trim() != "")
    //        strCondition += " AND Name like '%" + DBModule.RefineString(txtPortSearch.Text.ToString().Trim()) + "%'";
    //    if (drRegionSearch.SelectedValue != "")
    //        strCondition += " AND Region='" + DBModule.RefineString(drRegionSearch.SelectedValue.ToString()) + "'";
    //    #region Build List
    //    int nNumOfPages = 0;

    //    DataTable dtList;
    //    BuildList(strCondition, NumOfItemsPerPage, nPage, out nNumOfPages, out dtList, null, null);
    //    if (nPage > nNumOfPages) nPage = 1;

    //    rptData.DataSource = dtList;
    //    rptData.DataBind();
    //    #endregion
    //    #region Build Pager
    //    CommonFunctions.BuildPager(Request, nNumOfPages, nPage, strPageID, ContainerPage, out strPager);
    //    #endregion
    //}
    //protected void loadDropdownRegion()
    //{
    //    string sql = "";
    //    DataSet ds = null;
    //    sql = "SELECT DISTINCT Region FROM tbl_Ports ORDER BY Region";
    //    ds = DBModule.ExecuteQuery(sql, GV.cn, GV.trans);
    //    DataTable dtb = ds.Tables[0];
    //    drRegionSearch.DataSource = dtb;
    //    drRegionSearch.DataTextField = dtb.Columns[0].ToString();
    //    drRegionSearch.DataBind();
    //    drRegionSearch.Items.Insert(0, new ListItem("Select Region", ""));
    //}
}
